package com.gmrz.uaf.db.dao;

import com.gmrz.uaf.db.DAOException;
import com.gmrz.uaf.protocol.v1.processor.exception.UAFErrorCode;
import com.gmrz.uaf.remote.plugin.PluginData;
import com.gmrz.util.UUIDGenerator;
import com.gmrz.util.db.DBUtil;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.*;
import java.util.Calendar;

/**
 * Created by gongyuqiang on 2017/5/23.
 */
public class BasePluginDataDAO implements PluginDataDAO {

    private static final Logger LOG = LogManager.getLogger(BasePluginDataDAO.class);
    private static final String _SQL_INSERT="insert into t_plugin_data(pd_id,aaid,auth_type,oper_type,data1,data2,data3,data4,data5,createts)" +
            " values(?,?,?,?,?,?,?,?,?,?)";

    private Connection conn_;

    @AssistedInject
    public BasePluginDataDAO(@Assisted Connection conn_) {
        this.conn_ = conn_;
    }

    public BasePluginDataDAO() {

    }
    @Override
    public void insert(PluginData data) throws DAOException {
        String q = _SQL_INSERT;
        PreparedStatement s = null;
        try{
            int offset = 1;
            s = this.conn_.prepareStatement(q, 1);
            s.setString(offset++, UUIDGenerator.generateID());
            s.setString(offset++, data.getAaid());
            s.setString(offset++, data.getAuthType());
            s.setInt(offset++, data.getOperType());
            s.setString(offset++, data.getData1());
            s.setString(offset++, data.getData2());
            s.setString(offset++, data.getData3());
            s.setString(offset++, data.getData4());
            s.setString(offset++, data.getData5());

            Calendar calendar = Calendar.getInstance();
            Timestamp currentTimestamp = new Timestamp(calendar.getTime()
                    .getTime());

            s.setTimestamp(offset++, currentTimestamp);
            s.executeUpdate();
        }catch (SQLException sqle) {
            LOG.error("The following SQL statement failed to execute:\n {}",
                    q);
            throw new DAOException(UAFErrorCode.DB_INSERT_PLUGIN_DATA_FAILED,
                    sqle);
        } finally {
            DBUtil.close(s);
        }
    }
}
